package com.bang.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @ClassName: ForkJoinTaskExample
 * @Desc: 并行执行任务  大任务切割成小任务,合并小任务的结果 ,采用工作窃取算法,队列是双端队列
 *          A线程执行A队列中的任务 B线程执行B队列的任务  ,当B先执行完时,会从A队列底部窃取任务
 * @URL: https://www.cnblogs.com/cjsblog/p/9078341.html
 *
 * @auther: BANG
 * @Date: 2019/10/09 09:56
 * @Version: 1.0
 * @Modified By:
 */
@Slf4j
public class ForkJoinTaskExample extends RecursiveTask<Integer> {


    public static final int threshold = 2;
    private int start;
    private int end;

    public ForkJoinTaskExample(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        }else{
            int middle = start + (end - start) / 2;
            ForkJoinTaskExample left = new ForkJoinTaskExample(start, middle);
            ForkJoinTaskExample right = new ForkJoinTaskExample(middle + 1, end);

            left.fork();
            right.fork();

            Integer leftJoin = left.join();
            Integer rightJoin = right.join();
            sum = leftJoin + rightJoin;
        }
        return sum;
    }


    public static void main(String[] args) throws Exception {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTaskExample taskExample = new ForkJoinTaskExample(1, 100);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(taskExample);
        System.out.println(submit.get());
    }
}
